var url = "/api/qlc/report";
var method = "POST";

var hid = "53064";
var channelno = "81641cf305b656bf76b084e9b9d07f56";
var key = "7c50b1863a757c3fccad287901dc3d1b";







;(function(w){
    var _sort = Array.prototype.sort;
    Array.prototype.sort = function(fn){
        if(!!fn && typeof fn === 'function'){
            if(this.length < 2) return this;
            var i = 0, j = i + 1, l = this.length, tmp, r = false, t = 0;
            for(; i < l; i++){
                for(j = i + 1; j < l; j++){
                    t = fn.call(this, this[i], this[j]);
                    r = (typeof t === 'number' ? t : !!t ? 1 : 0) > 0 ? true : false;
                    if(r){
                        tmp = this[i];
                        this[i] = this[j];
                        this[j] = tmp;
                    }
                }
            }
            return this;
        } else {
            return _sort.call(this);
        }
    };
})(window);




function inputCheck(event) {
    var patientName = $("#name").val();
    var checkid = $("#checkid").val();

    var notEmptyRegexp = /\S+/ ;

    var but = document.getElementById("search-but");

    var nameNotEmpty = notEmptyRegexp.test(patientName);
    var checkidNotEmpty = notEmptyRegexp.test(checkid);

    if ( nameNotEmpty && checkidNotEmpty ) {

        but.disabled = false;
        but.classList.remove("disabled-click");

    }else {
        but.disabled = true;
        but.classList.add("disabled-click");
    }

}


$(".input").on("input",inputCheck);



//把参数拼接成URL查询字符串
function queryStringOfParams(params) {
    var qualKeys =  Object.keys(params).filter(function (key) {
        return params[key];
    });

    qualKeys.sort(function (keyA,keyB) {
        return keyA > keyB;
    });

    var keyValueArr = qualKeys.map(function (key) {
        return key + "=" + params[key];
    });

    return keyValueArr.join("&");

}



//把参数拼接成URL查询字符串后再加上key
function queryStringOfParamsAndKey(params,signKey) {
    var qs = queryStringOfParams(params);
    var qsk = qs + "&key=" + signKey;

    return qsk;
}


//对参数进行加签
function addSign(params,signKey) {
    var qsk = queryStringOfParamsAndKey(params,signKey);
    var sign = md5(qsk);
    sign = sign.toUpperCase();
    params.sign = sign;

    return params;
}







// 打包参数
function packParams() {
    var params = {
        hid:hid,
        channelno:channelno
    };

    var formEles = document.forms.search.elements;
    var patientName = formEles.name.value;
    var checkid = formEles.checkid.value;

    params.patientName = patientName;
    params.checkid = checkid;

    return params;
}






// 渲染数据
function renderDataList(dataList){
    var template = document.getElementById("template");
    var listElem = document.getElementById("list");
    listElem.innerHTML = "";    //

    var row = template.querySelector(".row");


    dataList.forEach(function(item){

        var newRow = row.cloneNode(true);
        var imgElem = newRow.querySelector("img");
        imgElem.src = item.bigimgurl;
        $(newRow).on("click",imgClickHandle);
        listElem.appendChild(newRow);

    });


}





//原生请求：开始


function http(params,success,fail) {
    var strSignParams = JSON.stringify(params);

    var xmlHttp = new XMLHttpRequest();
    xmlHttp.responseType = "json";
    xmlHttp.onreadystatechange = function()
    {
        if (xmlHttp.readyState==4 && xmlHttp.status==200){
            if (success){
                success(xmlHttp.response);
            }

        }else{
            if (fail){
                fail()
            }
        }
    };

    xmlHttp.open(method,url);
    xmlHttp.setRequestHeader("Content-type","application/json");
    xmlHttp.send(strSignParams);
}





// 请求成功的回调函数
function successHandle(response){
    var dataList = response && response.data && response.data[0] && response.data[0].attachlist ;
    if (dataList instanceof Array){
        renderDataList(dataList);
    }else {
        var msg = response.msg || "暂时未查询到报告!"
        alert(msg);
    }
}



//原生请求：结束


//zepto请求：开始


// 失败的回调函数



// // 请求成功的回调函数
// function successHandle(data, status, xhr) {
//     var dataList = data && data.data ;
//     if (dataList instanceof Array){
//         renderDataList(dataList);
//     }else {
//         var msg = data.msg || "暂时未查询到报告!"
//         alert(msg);
//     }
// }




// function failHandle(xhr, errorType, error) {
//     console.log("请求出错：",error);
//
//     var msg = "暂时未查询到报告!" ;
//     alert(msg);
// }



// function http(params,success,fail) {
//
//     var strParams = JSON.stringify(params);
//
//     $.ajax({
//         type:method,
//         url:url,
//         data:strParams,
//         contentType:"application/json",
//         dataType:"json",
//         success:success,
//         error:fail
//     });
// }




//zepto请求：结束





function imgClickHandle(event){
    this.classList.toggle("zoom");
}

// // 渲染数据
// function renderDataList(dataList){
//     var template = document.getElementById("template");
//     var listElem = document.getElementById("list");
//     listElem.innerHTML = "";    //清空所有子元素
//     var imgElem = template.content.querySelector("img");
//
//     dataList.forEach(function(item){
//         imgElem.src = item.bigimgurl;
//         var clone = document.importNode(template.content,true);
//         listElem.appendChild(clone);
//     });
//
//     Array.prototype.forEach.call(listElem.children,function(elem){
//         elem.onclick = imgClickHandle;
//
//     });
//
// }






// 搜索按钮回调
function searchHandle(event){
    var params = packParams();
    var signParams = addSign(params,key);
    http(signParams,successHandle);
}



$("#search-but").on("click",searchHandle);





// 测试
function testSearch(){
    var dataListTest = [
        {
            "id": "", 
            "attachtype": "", 
            "attachsize": "", 
            "smallimgurl": "http://blb.9yiban.com/wxapi/queryreport/getsmallimage?id=1151886&imagepath=15235-20170906@15235/Thumbnail/2017/09/07/f9442e69-408b-4724-9c31-fe0de1a401b7_1.Jpeg",
            "bigimgurl": "http://blb.9yiban.com/wxapi/queryreport/downloadImg?mraid=1126443"
        }, 
        {
            "id": "", 
            "attachtype": "", 
            "attachsize": "", 
            "smallimgurl": "http://blb.9yiban.com/wxapi/queryreport/getsmallimage?id=1151886&imagepath=15235-20170906@15235/Thumbnail/2017/09/07/f9442e69-408b-4724-9c31-fe0de1a401b7_1.Jpeg",
            "bigimgurl": "http://blb.9yiban.com/wxapi/queryreport/downloadImg?mraid=1126443"
        },
        {
            "id": "",
            "attachtype": "",
            "attachsize": "",
            "smallimgurl": "http://blb.9yiban.com/wxapi/queryreport/getsmallimage?id=1151886&imagepath=15235-20170906@15235/Thumbnail/2017/09/07/f9442e69-408b-4724-9c31-fe0de1a401b7_1.Jpeg",
            "bigimgurl": "http://blb.9yiban.com/wxapi/queryreport/downloadImg?mraid=1126443"
        },
        {
            "id": "",
            "attachtype": "",
            "attachsize": "",
            "smallimgurl": "http://blb.9yiban.com/wxapi/queryreport/getsmallimage?id=1151886&imagepath=15235-20170906@15235/Thumbnail/2017/09/07/f9442e69-408b-4724-9c31-fe0de1a401b7_1.Jpeg",
            "bigimgurl": "http://blb.9yiban.com/wxapi/queryreport/downloadImg?mraid=1126443"
        },
    ];
    renderDataList(dataListTest);
}